package com.jerkin.coder;

import com.jerkin.serial.ObjectSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @version V1.0
 * @ClassName: EncoderHelper
 * @Description:编码工具类
 * @author: huhongzhi
 * @date: 2021/4/17 16:20
 */
public class EncoderHelper extends MessageToByteEncoder {

    private Class<?> clazz;

    private ObjectSerializer objectSerializer;

    public EncoderHelper(Class<?> clazz, ObjectSerializer serializer) {
        this.clazz = clazz;
        this.objectSerializer = serializer;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if (clazz != null && clazz.isInstance(o)) {
            byte[] bytes = objectSerializer.serialize(o);
            byteBuf.writeInt(bytes.length);
            byteBuf.writeBytes(bytes);
        }
    }
}
